'use strict'

const {logger} = require('ee-core/log')
const path = require('node:path')
const {windowService} = require('../service/os/window')
const {merge} = require('lodash')
const {BrowserWindow, webContents} = require('electron')
const {isProd, isDev, getBaseDir} = require('ee-core/ps')
const Utils = require('ee-core/utils')
const {getConfig} = require('ee-core/config')
const {appService} = require('../service/app')
const Locks = require('../service/os/lockWindow')
const {preventTitleBarContextMenuFunc, registerWindowOpenHandler} = require('../service/os/browser')
const {loadFile} = require("ee-core/loader")

/**
 * 子窗口
 */
class ChildWindowController {
    /**
     * 创建子窗口
     */
    async create(args, event) {
        let {id, indexPath, type = 'frontend', options = {}, asyncWindow = true} = args
        const Conf = getConfig()
        type = type.toLowerCase()
        const normalIndexPath = indexPath.toLowerCase()
        const currentWindow = BrowserWindow.fromWebContents(event.sender)
        switch (type) {
            case 'frontend':
                if (isProd()) {
                    //生产环境
                    const mainServer = Conf.mainServer
                    if (Utils.isFileProtocol(mainServer.protocol)) {
                        indexPath = mainServer.protocol + path.join(getBaseDir(), mainServer.indexPath) + `#${indexPath}`
                    } else {
                        indexPath = mainServer.protocol + mainServer.host + ':' + mainServer.port + indexPath
                    }
                } else {
                    //开发环境
                    const binFile = path.join(getBaseDir(), "./cmd/bin.js")
                    const binConfig = loadFile(binFile)
                    const {dev} = binConfig
                    // tips: match with ee-bin
                    const frontendConf = merge({
                        protocol: 'http://',
                        hostname: 'localhost',
                        port: 8080,
                        indexPath: 'index.html'
                    }, dev.frontend)
                    const url = frontendConf.protocol + frontendConf.hostname + ':' + frontendConf.port
                    indexPath = url + `#${indexPath}`
                }
                break
            case 'web':
                // 默认为http协议
                if (!normalIndexPath.startsWith('http')) {
                    if (!normalIndexPath.startsWith('//')) {
                        indexPath = 'http://' + indexPath
                    } else {
                        indexPath = 'http:' + indexPath
                    }
                }
                break
            case 'html':
                // 默认为file协议
                if (!normalIndexPath.startsWith('file://')) {
                    indexPath = 'file://' + path.join(getBaseDir(), indexPath)
                }
                break
            default:
                throw new Error('Undefined window type.')
        }
        const OPTIONS = {
            minWidth: 980,
            minHeight: 650,
            fullscreenable: false,
            show: false,
            frame: false,
            backgroundColor: appService.appBackgroundColor
        }
        //除非设置center为true，否则窗口将自适应屏幕位置
        if (options.center !== true) {
            const mainWinRectangle = currentWindow.getNormalBounds()
            OPTIONS.x = mainWinRectangle.x < 150 ? (mainWinRectangle.x + 50) : (mainWinRectangle.x - 50)
            OPTIONS.y = mainWinRectangle.y < 150 ? (mainWinRectangle.y + 50) : (mainWinRectangle.y - 50)
        }
        if (options.parent) {
            const webContentId = windowService.getWCid(options.parent)
            options.parent = webContentId ? BrowserWindow.fromWebContents(webContents.fromId(webContentId)) : null
        }
        merge(OPTIONS, options)
        try {
            let childWin
            if (Locks.has(id)) {
                childWin = Locks.get(id)
                childWin.show()
                childWin.focus()

                return {
                    state: true,
                    message: 'success'
                }
            } else {
                //当前渲染进程(子)窗口标识
                process.env.EE_WINDOW_KEY = id
                childWin = windowService.create(id, OPTIONS)
                //锁定窗口
                Locks.add(id, childWin)
                //当构建窗口选项`show`为`false`时显示窗口(不白屏)
                if (OPTIONS.show === false) {
                    childWin.once('ready-to-show', () => {
                        childWin.show()
                        childWin.focus()
                    })
                }
                if (asyncWindow) {
                    //异步加载渲染
                    childWin.loadURL(indexPath)
                }
            }
            //阻止窗口标题栏右键默认上下文菜单
            preventTitleBarContextMenuFunc(childWin, () => {
                logger.info(ChildWindowController.toString(), 'system-context-menu be rejected')
            })
            //注册网页<a target="_blank">标签和window.open拦截处理器
            registerWindowOpenHandler(childWin)
            if (!asyncWindow) {
                //同步加载渲染
                await childWin.loadURL(indexPath)
            }
            if (isDev()) {
                childWin.webContents.openDevTools({
                    mode: 'undocked'
                })
            }
            return {
                state: true,
                message: 'success'
            }
        } catch (e) {
            const errorStr = e.toString() || e
            logger.error(ChildWindowController.toString(), errorStr)
            return {
                state: false,
                message: errorStr
            }
        }
    }
}

ChildWindowController.toString = () => '[class ChildWindowController]'
module.exports = ChildWindowController
